
import Vue from "vue";
import Vuex from 'vuex';
import axios from "axios";
import request from "../utils/request";

import { GetToken, SetToken, removeToken } from "@/utils/auth";
import { getUser, setUser } from "@/api/admin/User";
import { login, logout } from "@/api/admin/Login";
Vue.use(Vuex);

const store = new Vuex.Store({

    state: {
        StoreId: 0,
        Update: {
            name: '',
            address: '',
            date: '',
            select: '',
            id: 0
        },
        user: {}
    },
    mutations: {
        setUser(state, userData) {
            state.user = userData;
        }
    },
    actions: {
        Login({ commit }, RootInfo) {
            return new Promise((resolve, reject) => {
                login(RootInfo.rootname, RootInfo.rootpwd)
                    .then(res => {
                        console.log('res.data.data', res);
                        // ✅ 结构校验
                        if (!res.data.data.token) {
                            reject(new Error('令牌不存在'));
                            return;
                        }
                        // ✅ 优先存储 Token
                        SetToken(res.data.data.token);
                        console.log('存储后的Token:', GetToken()); // 这里应该能获取到
                        // ✅ 使用封装后的 request 实例（自动携带 Token）
                        resolve(res.data.data)
                    })
                    .catch(error => reject(error));
            })
        },

        initUser({ commit }) {
            getUser()
                .then(userData => {
                    commit('setUser', userData);
                })
                .catch(error => {
                    console.error('获取用户数据时出错:', error);
                });
        },

    }, plugins: [
        (store) => {
            // 在页面刷新前保存数据到本地存储
            window.addEventListener('beforeunload', () => {
                localStorage.setItem('vuexState', JSON.stringify(store.state));
            });

            // 页面加载时从本地存储恢复数据
            const savedState = localStorage.getItem('vuexState');
            if (savedState) {
                store.replaceState(JSON.parse(savedState));
            }
        }
    ]
});

export default store;